import React, { useEffect } from 'react'
import { ScrollView, View, Image, Ad } from '@tarojs/components'
import { useDidShow } from '@tarojs/taro'
import { SpTab, SpNote, SpToast, SpNavBar, } from '@/components'
import { SelectInput, CommonButton } from '@/components/sp-page-components'
import { getThemeStyle, pickBy, showToast, hasNavbar } from '@/utils'
import { useSelector } from 'react-redux'
import { useImmer } from 'use-immer'
import { usePage, useDepChange } from '@/hooks'
import FilterBlock from '../order/list/comps/filterblock'
import api from '@/api'
import { PullToRefresh, InfiniteScroll, Modal, Radio, Space, Form, Stepper, Dialog, Badge } from 'antd-mobile'
import './index.scss'
//页面类型
const PAGE_TYPE = 'shopList'



const ACTION_LIST = [
    { label: '状态', plain: true, type: 'delete' },
    { label: '编辑', plain: true, type: 'edit' }
]
const statusRecord = {
    pulling: '用力拉',
    canRelease: '松开吧',
    refreshing: '玩命加载中...',
    complete: '好啦',
}

const initState = {
    //搜索框选择的参数  类型为对象
    inputParams: null,
    //搜索框输入的值
    inputValue: undefined,
    list: [],
    //tab切换
    activeIndex: 0,
    //筛选参数
    filterParams: null,
    visible: false,
    is_valid: '',
    is_ziti: '',
    is_delivery: ''
}
const ShopList = (props) => {
    const [state, setState] = useImmer(initState)

    const { inputParams, inputValue, list, activeIndex, filterParams } = state
    const { formType} = props

    const handleParamChange = (inputParams) => {
        setState((_val) => {
            _val.inputParams = { ...inputParams }
        })
    }

    const {
        activeShop: { distributor_id }
    } = useSelector((state) => state.planSelection)

    const fetch = async ({ pageIndex, pageSize }) => {
        let synthetic = {}
        if (inputParams && inputValue) {
            synthetic[inputParams.value] = inputValue
        }
        let audit_status = filterParams?.approve_status ? 'approved' : undefined
        const params = {
            page: pageIndex,
            pageSize,
            ...synthetic,
            ...(filterParams || {}),
        }
        const { list, total_count } = await api.shop.getShopList(params)

        await setState((_val) => {
            _val.list = params.page > 1 ? [..._val.list, ...list] : list
        })
        // console.log('-------', pageIndex, list)
        // this.setState({
        //   orderList: params.page_no > 1 ? [...this.state.orderList, ...list] : list
        // })

        return { total: total_count }
    }

    const { page, getTotal, nextPage, resetPage, nextPageForce } = usePage({
        fetch
    })

    useDidShow(async () => {
        // await setState((draft) => {
        //     draft.list = []
        // })
        // resetPage()
    })
    useEffect(() => {
        // await setState((draft) => {
        //     draft.list = []
        // })
        resetPage()
    }, [])
    const reloadpage = async() =>{
        let synthetic = {}
        if (inputParams && inputValue) {
            synthetic[inputParams.value] = inputValue
        }
        let audit_status = filterParams?.approve_status ? 'approved' : undefined
        const params = {
            page: 1,
            pageSize: 10,
            ...synthetic,
            ...(filterParams || {}),
        }
        const { list, total_count } = await api.shop.getShopList(params)
        await setState((_val) => {
            _val.list = params.page > 1 ? [..._val.list, ...list] : list
        })
        // console.log('-------', pageIndex, list)
        // this.setState({
        //   orderList: params.page_no > 1 ? [...this.state.orderList, ...list] : list
        // })

        return { total: total_count }
    }
    const onPullDownRefresh = async () => {
        // await setState((draft) => {
        //     draft.list = []
        // })
        await resetPage()

    }
    const handleValueChange = (inputValue) => {
        setState((_val) => {
            _val.inputValue = inputValue
        })
    }

    const handleSearchFilter = async () => {
        await setState((draft) => {
            draft.list = []
        })
        resetPage()
    }

    const handleSubmitParams = async (params) => {
        await setState((_val) => {
            _val.filterParams = params
        })
    }

    useDepChange(() => {
        if (filterParams) {
            handleSearchFilter()
        }
    }, [filterParams])

    const editShopValid = async (params) => {

        await api.shop.editMerchant(params)
    }
    const handleAction = async (info, { type, label }, index) => {
        if (type === 'edit') {
            navigateToGoodForm(info.distributor_id)
        } else if (type === 'delete') {
            let lll = { ...info }
            let yyy = [...list]
            Dialog.confirm({
                //   title: '选择优惠券类型',
                title: '修改状态',
                content: (
                    <Radio.Group defaultValue={info.is_valid} onChange={(e) => {
                        lll.is_valid = e
                        yyy[index] = lll

                    }}>
                        <Space direction='horizontal' align='center' justify='center'>
                            <Radio value='true'>启用</Radio>
                            <Radio value='false'>禁用</Radio>
                            <Radio value='delete'>废弃</Radio>
                        </Space>
                    </Radio.Group>
                ),
                showCloseButton: true,
                onConfirm: async () => {
                    if (info.is_valid == lll.is_valid) {
                        return
                    } else {
                        await editShopValid({ 'is_valid': lll.is_valid, distributor_id: info.distributor_id })
                        setState((val) => {
                            val.list = yyy
                        })
                    }

                },
                onCancel: () => {

                },
                confirmText: '修改',
                cancelText: '取消',
                closeOnAction: true,
            })
        } else {
            showToast(`${label}，无法上下架！`)
        }
    }
    const navigateToGoodForm = (id) => {
        if (!id) {
            Taro.navigateTo({
                url: `/pages/shop/form`
            })
            return

        }
        Taro.navigateTo({
            url: `/pages/shop/edit/editList?id=${id}`
        })
        
    }

    return (

        <View>
            <SpNavBar leftIconType = {formType == 'index' ? '': 'chevron-left'} onClickLeftIcon={formType == 'index' ? ()=>{}:''} title='店铺列表' />
            <View className='page-shop-list' style={getThemeStyle()}>
                <View className='page-shop-list-head'>
                    <View className='page-shop-list-input'>
                        <SelectInput
                            inputParam={inputParams}
                            inputValue={inputValue}
                            pageType={PAGE_TYPE}
                            paramChange={handleParamChange}
                            valueChange={handleValueChange}
                            onInputConfirm={handleSearchFilter}
                        />
                    </View>

                    <FilterBlock title='店铺筛选' pageType={PAGE_TYPE} onSubmitParams={handleSubmitParams} />
                </View>
                <View className='scollerView'>
                    <PullToRefresh
                        onRefresh={onPullDownRefresh}
                        renderText={status => {
                            return <div>{statusRecord[status]}</div>
                        }}
                    >
                        <ScrollView
                            className='page-shop-list-list'
                            scrollY
                            scrollWithAnimation
                        >
                            {list.length > 0 ? (
                                list.map((shopInfo, index1) => {
                                    return (
                                        <View className='comp-item' key={shopInfo.distributor_id}>
                                            <View className='comp-item-good-header'>


                                                <Badge
                                                    color={shopInfo.is_valid === 'true' ? '#21B991' : (shopInfo.is_valid === 'false' ? '#b3b500' : '#c50000')}
                                                    content={shopInfo.is_valid === 'true' ? '启用' : (shopInfo.is_valid === 'false' ? '禁用' : '废弃')}
                                                    style={{ '--right': '100%', }}
                                                >
                                                    <View className='comp-item-good-header-pic'>

                                                        <Image className='img' src={shopInfo.logo} />
                                                    </View>
                                                </Badge>
                                                {/* <View className='shop-tag'>{item.is_valid === 'true' ? '启用' : (item.is_valid === 'false' ? '禁用' : '废弃')}</View> */}


                                                <View className='comp-item-good'>
                                                    <View className='comp-item-good-center'>
                                                        <View className='good-name'>{shopInfo.store_name}</View>
                                                        <View className='good-no'>{shopInfo.store_address}</View>
                                                    </View>
                                                    <View className='comp-item-good-right'>
                                                        <View className='sale_price'>
                                                            <View className='sale_price_label'>姓名:{shopInfo.contact}</View>
                                                            <View className='sale_price_number'>是否自提:{shopInfo.is_ziti ? '是' : '否'}</View>
                                                        </View>
                                                        <View className='sale_price'>
                                                            <View className='sale_price_label'>电话:{shopInfo.phone}</View>
                                                            <View className='sale_price_number'>快递配送:{shopInfo.is_delivery ? '是' : '否'}</View>
                                                        </View>
                                                    </View>
                                                </View>
                                            </View>

                                            <View className='comp-item-action'>
                                                {ACTION_LIST.map((item, index) => {
                                                    return (
                                                        <CommonButton
                                                            text={item.label}
                                                            size='small'
                                                            type={item.type === 'delete' ? 'danger' : 'primary'}
                                                            plain={item.plain}
                                                            key={index}
                                                            className='common-button'
                                                            onClick={() => handleAction(shopInfo, item, index1)}
                                                        />
                                                    )
                                                })}
                                            </View>
                                        </View>
                                    )
                                })

                            ) : (
                                <SpNote className="note-list" img='empty.png'>暂无数据～</SpNote>
                            )}
                           
                            {!!list.length && <InfiniteScroll loadMore={nextPageForce} hasMore={page.hasMore} />}

                        </ScrollView>
                    </PullToRefresh>
                </View>
                <View className='page-shop-list-addbutton'>
                    {/* <View className='iconfont icon-tianjia'></View> */}
                    <View className='text' onClick={() => navigateToGoodForm()}>
                        添加店铺
                    </View>
                </View>

                <SpToast />
            </View>
        </View>
    )
}

export default ShopList
